package ocg.common.re.jdbc;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chenbo on 2018/3/1.
 * jdbc 查询 feed 供给器
 */
public class JdbcQuery {

    Logger logger = LogManager.getLogger ( this.getClass () );

    Connection connection;


    public JdbcQuery(String url, String user, String password) {
        connection = new  JdbcBuilder( url , user , password ).build ();
    }

    public JdbcQuery( Connection connection ){
        this.connection = connection ;
    }

    /**
     * 列名与值 对应 ， 返回 Map<String,Object>
     * @param set
     * @return
     * @throws SQLException
     */
    public Map<String,Object> getFeed( List<String> row , ResultSet set ) throws SQLException {
        Map<String,Object> map = new HashMap <String, Object> (  );
        for ( String rows : row ){
                String[] rowset = rows.split ( ":" );
                String rowName = rowset[0];
                String rowType = rowset[1];
                Object o = value ( rowName, rowType, set );
            map.put ( rowName , o );
        }
        return map;
    }

    /**
     * 获取不同类型的列数据 ， 并以 object 类型返回
     * @param rowName
     * @param rowType
     * @param set
     * @return Object
     * @throws SQLException
     */
    public Object value( String rowName , String rowType , ResultSet set) throws SQLException {

        if ( rowType.equals ( "int" ) ){
            return set.getInt ( rowName );
        }
        if ( rowType.equals ( "nvarchar" ) ){
            return set.getString ( rowName );
        }
        if ( rowType.equals ( "varchar" ) ){
            return set.getString ( rowName );
        }
        if ( rowType.equals ( "longvarchar" ) ){
            return set.getString ( rowName );
        }
        if ( rowType.equals ( "datetime" ) ){
            return set.getTimestamp ( rowName );
        }
        if ( rowType.equals ( "timestamp" ) ){
            return set.getString ( rowName );
        }
        if (rowType.equals ( "ntext" )) {
            return set.getString ( rowName );
        }
        if (rowType.equals ( "text" )) {
            return set.getString ( rowName );
        }
        if (rowType.equals ( "decimal" )) {
            return set.getBigDecimal ( rowName );
        }
        if (rowType.equals ( "bit" )) {
            return set.getBoolean ( rowName );
        }
        return set.getString ( rowName );
    }

    /**
     * 通过 sql 查询出所有数据
     * @param sql
     * @return
     */
    public List<Map<String,Object>> query( String sql ){

        List<Map<String,Object>> sowList = new ArrayList <Map <String, Object>> (  );
        JdbcService jdbcService = new JdbcService ( connection );

        ResultSet set =jdbcService.getResultSet (sql );

        if (set != null) {

            List<String> row = new ArrayList <String> (  );

            try {
                //获取数据库表列名
                ResultSetMetaData metaData = set.getMetaData ();
                //获取列数
                int count = metaData.getColumnCount ();
                logger.info ( "查询结果，列数：" + count );
                 /* 遍历所有查询出来的 列名和数据类型 */

                for (int i = 1 ; i <= count; i++) {
                    String rowName = metaData.getColumnName ( i ) ;
                    String rowType = metaData.getColumnTypeName ( i );
                    row.add ( rowName + ":" + rowType );
                }
            } catch (SQLException e) {
                logger.error ( "处理数据库表列名 错误 SQLException" );
                e.printStackTrace ();
            }

                if (row != null) {
                    try {
                        while ( set.next () ) {
                            Map<String,Object> o =  getFeed ( row, set );
                            sowList.add ( o );
                        }
                    } catch (SQLException e) {
                        e.printStackTrace ();
                    }
                } else {
                    logger.error ( "列名为空" );
                }

        } else {
            logger.debug ( "查询结果为空，请检查 sql 查询语句是否正确，或环境是否正确 ！");
        }
        logger.info ( "查询结果，行数：" + sowList.size () );
//        if (connection != null) {
//            try {
//                connection.close ();
//                logger.info ( "关闭数据库链接" );
//            } catch (SQLException e) {
//                logger.info ( "关闭数据库链接异常 SQLException" );
//                e.getErrorCode ();
//            }
//        }
        return sowList;
    }

}
